package com.ruoyi.wechat.api;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpInteractionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Formatter;
import java.util.Random;


/**
 * @author Administrator
 * @name：WechatApi.java
 * @description：微信小程序API
 * @since 2017年11月14日
 */
@Component
//@ConfigurationProperties(prefix = "com.zyd")
@PropertySource(value = {"classpath:wechat.properties"})
public class WechatXcxApi {
    /**
     * 静态变量、类变量不是对象的属性，而是一个类的属性，
     * 所以静态方法是属于类（class）的，普通方法才是属于实体对象（也就是New出来的对象）的，
     * spring注入是在容器中实例化对象，所以不能使用静态方法。
     */
    private static Environment env;

//	private static MemCachedClient memClient;

    public static String getAppid() {
        return env.getProperty("xcxAppId");
    }

    /**
     * 获取小程序二维码生成路径
     *
     * @return
     */
    public static String getwxacodeunlimitUrl() {
        return String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", access_token());
    }

    /**
     * 下发小程序和公众号统一的服务消息
     */
    public static String send_template_msg() {
        return String.format("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=%s", access_token());
    }

    /**
     * 小程序获得用户的OPENID
     *
     * @param js_code 小程序端的
     * @return
     */
    public static String jscode2session(String js_code) {
        String appid = env.getProperty("xcxAppId");
        String xcxAppSecret = env.getProperty("xcxAppSecret");
        return String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appid,
                xcxAppSecret, js_code);
    }


    /**
     * 小程序的接口调用凭证
     *
     * @return
     */
    public static String access_token() {
        Object access_token = CacheUtils.get(Constants.WECHAT__ACCESS_TOCKEN);
        if (access_token == null) {
            access_token = getAccessToken();
        } else {
            String a_ = access_token.toString();
            access_token = a_.substring(0, a_.indexOf("expriy:"));
            String expriy = a_.substring(a_.indexOf("expriy:") + 7);
            Date now = new Date(); //处理时间在有效期之后
            if (now.after(DateUtils.parseDate(expriy))) {
                access_token = getAccessToken();
            }
        }
        return access_token.toString();
    }

    private static Object getAccessToken() {
        Object access_token;
        String appid = env.getProperty("xcxAppId");
        String secret = env.getProperty("xcxAppSecret");
        String sendUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret);
        String resultJson = HttpInteractionUtil.getDate(sendUrl, "utf-8");
        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        if (jsonObject == null) {
            throw new BusinessException("微信公众号获取用户信息失败");
        }

        access_token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");// 有效期（秒）
        String expriy = null;
        try {
            Date date = DateUtils.addSeconds(DateUtils.getNowDate(), Integer.valueOf(expires_in) - 10);
            expriy = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date);
        } catch (Exception e) {
        }

        CacheUtils.put(Constants.WECHAT__ACCESS_TOCKEN, access_token + "expriy:" + expriy);
        return access_token;
    }


    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //随机字符串生成
    public static String getRandomString(int length) { //length表示生成字符串的长度      
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//		String string1 = "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9qxCw46hU3Z4mkDjScP4QMht3eoVAj1Tphyzzb4UxM_SI24FMqh5s4a4Evb4mT_p2Q&noncestr=0e182a9c-315a-4e94-b38b-8d859af2dcd2&timestamp=1511624798&url=http://192.168.0.100:8181/wechatsdk/share.htm";
//		MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//		crypt.reset();
//		crypt.update(string1.getBytes("UTF-8"));
//		String signature = byteToHex(crypt.digest());
//		System.out.println(signature);

        Date date = DateUtils.addSeconds(DateUtils.getNowDate(), (Integer.valueOf(7200) - 10));
        System.out.println(DateUtils.getTime());
        System.out.println(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
    }

    public static Environment getEnv() {
        return env;
    }

    @Autowired
    public void setEnv(Environment env) {
        WechatXcxApi.env = env;
    }

}
